#include <stdlib.h>


#include <board.h>


//************* TimePV **************
void TimePV_StartDelayCounter(int i_timeUs)
{
	TIMER1->CTL = TIMER_CTL_RSTCNT_Msk;
	TIMER1->CTL = TIMER_ONESHOT_MODE | 8;
	TIMER1->CMP = i_timeUs;
	TIMER_Start(TIMER1);
	while (TIMER1->CTL & TIMER_CTL_ACTSTS_Msk)
		;
	// while (!(TIMER1->INTSTS & TIMER_INTSTS_TIF_Msk))
	// 	;
	// TIMER1->INTSTS = TIMER_INTSTS_TIF_Msk;
}

void TimePV_WaitForFinish(void)
{
	while (!(TIMER1->INTSTS & TIMER_INTSTS_TIF_Msk))
		;
	TIMER1->INTSTS = TIMER_INTSTS_TIF_Msk;
}

void TimePV_WaitForFinishAtLeast(int i_timeUs)
{
	int t_now, t_dis;
	t_now = (TIMER1->CNT)/8;
	t_dis = (TIMER1->CMP) / 8;
	if (i_timeUs > (t_dis - t_now))
	{
		TIMER_Stop(TIMER1);
		TimePV_StartDelayCounter(i_timeUs);
//		TIMER_Start(TIMER1);
		while (TIMER1->CTL & TIMER_CTL_ACTSTS_Msk);
	}
	while (!(TIMER1->INTSTS & TIMER_INTSTS_TIF_Msk))
		;
	TIMER1->INTSTS = TIMER_INTSTS_TIF_Msk;
}

void TimePV_WaitForHalf()
{
	while((TIMER1->CNT/8)<(TIMER1->CMP/16));
}

//************* SYSTIM **************
void SYSTIM_StartDelayCounter(int i_timeUs)
{
	TIMER0->CTL = TIMER_CTL_RSTCNT_Msk;
	TIMER0->CTL = TIMER_ONESHOT_MODE | 8;
	TIMER0->CMP = i_timeUs;
	TIMER_Start(TIMER0);
	while (TIMER0->CTL & TIMER_CTL_ACTSTS_Msk)
		;
	while (!(TIMER0->INTSTS & TIMER_INTSTS_TIF_Msk))
		;
	TIMER0->INTSTS = TIMER_INTSTS_TIF_Msk;
}

// rt_thread_t led_thread, printf_thread;
void TIM0_Init(void)
{
  NVIC_EnableIRQ(TMR0_IRQn);

	TIMER0->CTL = TIMER_PERIODIC_MODE|(8);
	TIMER0->CMP = 100;
  TIMER_EnableInt(TIMER0);
}

void TIM0_InitXUs(uint32_t i_timeUs)
{
  NVIC_EnableIRQ(TMR0_IRQn);

	TIMER0->CTL = TIMER_PERIODIC_MODE|(8);
	TIMER0->CMP = i_timeUs;
  TIMER_EnableInt(TIMER0);
}

void TIM0_ChangeMatchValue(uint32_t i_value)
{
	TIMER0->CMP = i_value;
}


void TMR0_IRQHandler(void)
{
  if (TIMER_GetIntFlag(TIMER0) == 1)
  {
    TIMER_ClearIntFlag(TIMER0);
//    PE9 = ~PE9;
  }
}

void TIM0_Delay(uint32_t i_delayMs)
{
  TIMER0->CTL = TIMER_CTL_RSTCNT_Msk;
  TIMER0->CTL = TIMER_ONESHOT_MODE | 160;
  TIMER0->CMP = i_delayMs*50;
	TIMER_Start(TIMER0);
  while(TIMER0->CTL & TIMER_CTL_ACTSTS_Msk);
  while(!(TIMER0->INTSTS & TIMER_INTSTS_TIF_Msk));
  TIMER0->INTSTS = TIMER_INTSTS_TIF_Msk;
}
